import { SEP } from "../helpers/constents";

/**
 * 处理reducer
 *
 * @param {object} model 目标model
 */
export default function handleReducer(model) {
  const { reducers, flows, state: defaultState, namespace } = model;

  return (state = defaultState || 0, action = { type: null }) => {
    let tempState = {};
    const { type: typeInAction, payload } = action;
    const [namespaceInAction, realType] = typeInAction.split(SEP);
    const type = realType || namespaceInAction;

    for (let key in reducers) {
      if (key === type && namespaceInAction === namespace) {
        tempState = Object.assign({}, tempState, reducers[key](state, payload));
      }
    }

    for (let key in flows) {
      if (key === type && namespaceInAction === namespace) {
        tempState = Object.assign({}, tempState, flows[key](state, payload));
      }
    }

    return Object.assign({}, state, tempState);
  };
}
